<!-- src/components/UEditor.vue -->
<template>
  <div ref="editor"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue';

// 声明 UEditor 全局变量
declare const UE: any;

const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
});

const emit = defineEmits(['update:modelValue']);

const editor = ref(null);
let ueditorInstance: any = null;

onMounted(() => {
  nextTick(() => {
    initUEditor();
  });
});

onBeforeUnmount(() => {
  destroyUEditor();
});

const initUEditor = () => {
  nextTick(() => {
    ueditorInstance = UE.getEditor(editor.value, {
      initialFrameWidth: "95%",
      initialFrameHeight: 200,
      serverUrl: "pc/Fileimg/uderto", // 根据实际情况配置
    });

    ueditorInstance.ready(() => {
      ueditorInstance.setContent(props.modelValue);
      ueditorInstance.addListener('contentChange', () => {
        emit('update:modelValue', ueditorInstance.getContent());
      });
    });
  });
};

const destroyUEditor = () => {
  UE.delEditor(editor.value);
  //   if (ueditorInstance) {
  //     // 尝试在下一次事件循环中销毁实例，确保不会影响其他操作
  //     nextTick(() => {
  //       ueditorInstance.destroy();
  //       ueditorInstance = null;
  //     });
  //   }
};

watch(
  () => props.modelValue,
  (newValue) => {
    if (ueditorInstance && newValue !== ueditorInstance.getContent()) {
      ueditorInstance.setContent(newValue);
    }
  }
);
</script>

<style scoped>
/* 可以根据需要添加样式 */
</style>
